﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Rpc.Client;
using Wicture.EPC.Common;
using Wicture.QPZS.EPC.Core;
using Wicture.QPZS.EPC.Services.UserAuth.Base;

namespace Wicture.QPZS.EPC.Services.UserAuth
{
    public class ZpyUserAuthProcessor : BaseUserAuthProcessor
    {
        public override void HandleVinQueryResult(RpcRepository repository, JObject vinInfo)
        {
            string vin = vinInfo.Value<string>("vin");
            string brandCode = vinInfo.Value<string>("brandCode");
            var data = repository.Call<JObject>(EpcConsts.ZPYService, zpc_api.Authorize, new { vin, brandCode, service = (int)EpcEnum.ZpcServiceCode.VinQuery, result = vinInfo })?.data;
            HandZpyResult(data);
        }

        public override void HandlePartListResult(RpcRepository repository, JArray data, string brandCode)
        {
            var res = repository.Call<JObject>(EpcConsts.ZPYService, zpc_api.Authorize, new { brandCode, service = (int)EpcEnum.ZpcServiceCode.PartList, result = data })?.data;

            HandZpyResult(res);

            bool queryOEM = true;
            string oemStockBrand = ConfigurationManager.Settings.Variables["BrandHasOEMStock"];
            if (string.IsNullOrEmpty(oemStockBrand) || !oemStockBrand.Split(new char[] { ',' }).Contains(brandCode, StringComparison.OrdinalIgnoreCase))
            {
                queryOEM = false;
            }
            if (data != null && data.Any())
            {
                data.ForEach(e => e["queryOEM"] = queryOEM);
            }
        }
        public override void BuildPartSearchResult(IDbRESTFulRepository repository, JObject data)
        {
            string oemStockBrand = ConfigurationManager.Settings.Variables["BrandHasOEMStock"];

            if (data != null && data["parts"] != null && data["parts"].Any())
            {
                data["parts"].ForEach(e =>
                {
                    string brandCode = e["brandCode"].ToObject<string>();

                    bool queryOEM = true;
                    if (string.IsNullOrEmpty(oemStockBrand) || !oemStockBrand.Split(new char[] { ',' }).Contains(brandCode, StringComparison.OrdinalIgnoreCase))
                    {
                        queryOEM = false;
                    }
                    e["queryOEM"] = queryOEM;
                });
            }

        }
        public override void HandlePartDetailResult(IDbRESTFulRepository repository, JObject data, string brandCode)
        {
            var res = ((RpcRepository)repository).Call<JObject>(EpcConsts.ZPYService, zpc_api.Authorize, new { brandCode, service = (int)EpcEnum.ZpcServiceCode.PartDetail, result = data })?.data;
            HandZpyResult(res);

            bool queryOEM = true;
            string oemStockBrand = ConfigurationManager.Settings.Variables["BrandHasOEMStock"];
            if (string.IsNullOrEmpty(oemStockBrand) || !oemStockBrand.Split(new char[] { ',' }).Contains(brandCode, StringComparison.OrdinalIgnoreCase))
            {
                queryOEM = false;
            }
            if (data != null)
            {
                data["queryOEM"] = queryOEM;
            }
        }
        public override void CheckSearchPartTimes(IDbRESTFulRepository repository, string brandCode, string keyword)
        {
            RpcClient rpcClient = new RpcClient();
            var res = rpcClient.Call<JObject>(EpcConsts.ZPYService, zpc_api.Authorize, new { brandCode, service = (int)EpcEnum.ZpcServiceCode.PartQuery, result = new { brandCode = brandCode, keyword = keyword } }, repository.HttpContext, repository.CurrentUser)?.data;
            HandZpyResult(res);
        }
        #region private
        void HandZpyResult(JObject obj)
        {
            if (obj != null && obj.Value<int>("code") != (int)EpcEnum.ZpcErrorCode.Ok)
            {
                int zpyErrorCode = obj.Value<int>("code");
                int errorCode = HandleErrorCode(zpyErrorCode);
                string errorMsg = EpcEnum.GetZpcErrorCode(zpyErrorCode);
                throw new LogicalException(errorMsg, errorCode);
            }
        }

        int HandleErrorCode(int zpyErrorCode)
        {
            int epcErrorCode = 0;
            if (zpyErrorCode == (int)EpcEnum.ZpcErrorCode.UnAuthorized)
            {
                epcErrorCode = 620;
            }
            return epcErrorCode;
        }
        #endregion
    }
}
